package com.hyopt.modules.sys.redis;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.log.StaticLog;
import com.hyopt.common.exception.MyException;
import com.hyopt.common.utils.RedisKeys;
import com.hyopt.common.utils.RedisUtils;
import com.hyopt.modules.sys.entity.SysConfigEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 系统配置Redis
 *
 * @author wanglei
 * @date 2019-06-03 17:57:00
 */
@Component
public class SysConfigRedis {
	@Autowired
	private RedisUtils redisUtils;

	public boolean saveOrUpdate(SysConfigEntity config) {
		if (ObjectUtil.isNull(config)) {
			throw new MyException("参数配置不能为空");
		}
		try {
			String key = RedisKeys.getSysConfigKey(config.getParamKey());
			redisUtils.set(key, config);
			return true;
		} catch (Exception e) {
			StaticLog.error(e, "redis写入异常");
		}
		return false;
	}

	public void delete(String configKey) {
		String key = RedisKeys.getSysConfigKey(configKey);
		redisUtils.delete(key);
	}

	public void delete(List<String> configKeyList) {
		if (CollUtil.isNotEmpty(configKeyList)) {
			List<String> list = CollUtil.newArrayList();
			for (String configKey : configKeyList) {
				list.add(RedisKeys.getSysConfigKey(configKey));
			}
			list = CollUtil.distinct(list);
			list = CollUtil.newArrayList(CollUtil.removeBlank(list));
			redisUtils.delete(list);
		}
	}

	public SysConfigEntity get(String configKey) {
		try {
			String key = RedisKeys.getSysConfigKey(configKey);
			return redisUtils.get(key, SysConfigEntity.class);
		} catch (Exception e) {
			StaticLog.error(e, "redis读取异常");
		}
		return null;
	}
}
